import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:permission_handler/permission_handler.dart';

class PermissionRequestWidget extends StatefulWidget {
  final Permission permission;
  final List<String> permissionList;
  final bool isCloseApp;
  final String leftButtonText;
  PermissionRequestWidget(
      {@required this.permission,
      @required this.permissionList,
      this.leftButtonText = "再考虑一下",
      this.isCloseApp = false});

  @override
  _PermissionRequestWidgetState createState() =>
      _PermissionRequestWidgetState();
}

class _PermissionRequestWidgetState extends State<PermissionRequestWidget>
    with WidgetsBindingObserver {
  bool _isGSetting = false;

  @override
  void initState() {
    super.initState();
    checkPermission();
    // 注册观察者
    WidgetsBinding.instance.addObserver(this);
  }

  // 复写观察者
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    if (state == AppLifecycleState.resumed && _isGSetting) {
      checkPermission();
    }
  }

  @override
  void dispose() {
    // 移除观察者
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }
  // 检查权限

  void checkPermission({PermissionStatus status}) async {
    // 权限
    Permission permission = widget.permission;
    if (status == null) {
      // 权限状态
      status = await permission.status;
    }
    // print(status);
    // openAppSettings();
    // if (status.isGranted) {
    //   // 第一次申请
    //   showPermissionAlert(widget.permissionList[0], "同意", permission);
    // } else

    if (status.isDenied) {
      // 第一次申请拒绝
      if (Platform.isIOS) {
        showPermissionAlert(widget.permissionList[2], "去设置中心", permission,
            isSetting: true);
        return;
      }
      showPermissionAlert(widget.permissionList[1], "同意", permission);
    } else if (status.isPermanentlyDenied) {
      // 第二次申请拒绝
      showPermissionAlert(widget.permissionList[2], "去设置中心", permission,
          isSetting: true);
    } else {
      // 通过
      Navigator.of(context).pop(true);
    }
  }

  void showPermissionAlert(
      String message, String rightString, Permission permission,
      {bool isSetting = false}) {
    showCupertinoDialog(
        context: context,
        builder: (BuildContext context) {
          return CupertinoAlertDialog(
            title: Text("温馨提示"),
            content: Container(
              padding: EdgeInsets.all(10),
              child: Text(message),
            ),
            actions: [
              // 左边按钮
              CupertinoDialogAction(
                  child: Text("${widget.leftButtonText}"),
                  onPressed: () {
                    if (widget.isCloseApp) {
                      closeApp();
                    } else {
                      Navigator.of(context).pop(false);
                    }
                  }),
              // 右边按钮
              CupertinoDialogAction(
                  child: Text(rightString),
                  onPressed: () {
                    //  关闭弹窗
                    Navigator.of(context).pop();
                    if (isSetting) {
                      openAppSettings();
                    } else {
                      // 申请权限
                      requestPermission(permission);
                    }
                  }),
            ],
          );
        });
  }

  // 退出应用
  void closeApp() {
    SystemChannels.platform.invokeMethod("SystemNavigator.pop");
  }

// 申请权限
  void requestPermission(Permission permission) async {
// 发起权限申请
    PermissionStatus status = await permission.request();
    // print('请求后的 $status');
    // 检验
    checkPermission(status: status);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.transparent,
    );
  }
}
